/*
 * FileUtils.h
 *
 *  Created on: Jun 18, 2013
 *      Author: alexandru
 */


#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "FileResult.h"
#include <stdio.h>

#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

#ifndef FILEUTILS_H_
#define FILEUTILS_H_



struct SimpleObject{
	string propertyName;
	string propertyValue;
};

FileResult stn_readFile(char *path);
vector<SimpleObject> stn_getVarsFromFile(char *path);
FileResult stn_getStdOutFromCommand(string command);


class ObjectsFromFile{
public:
	ObjectsFromFile(char *path){
		objectList=stn_getVarsFromFile(path);
	}

	~ObjectsFromFile(){}


	string getPropertyByName(string param_propertyName){
		for(unsigned int i=0; i<objectList.size(); i++){
			if(objectList.at(i).propertyName==param_propertyName){
				return objectList.at(i).propertyValue;
			}
		}
		return "undefined property name";
	}

private:
	vector<SimpleObject> objectList;
};


FileResult stn_getStdOutFromCommand(string command){
	FileResult result;

	FILE * stream;
	const int max_buffer = 256;
	char buffer[max_buffer];
	command.append(" 2>&1");
	stream = popen(command.c_str(), "r");
	if (stream) {
		while (!feof(stream)){
			if (fgets(buffer, max_buffer, stream) != NULL) {
				result.addLine(string(buffer));
			}
		}
		pclose(stream);
	}

	return result;
}


vector<SimpleObject> stn_getVarsFromFile(char *path){
	FileResult result=stn_readFile(path);
	vector<string> lines=result.getLines();
	vector<SimpleObject> objects;

	for(unsigned int i=0; i< lines.size(); i++){
		string propValue;
		string propName;
		string currentline=lines.at(i);
		string::size_type pos=currentline.find("=");
		if(pos != std::string::npos) {
				propName=currentline.substr(0, pos);
				propValue=currentline.substr(pos+1);
				propName.erase(std::remove(propName.begin(), propName.end(), '\n'), propName.end());//scoate enter final daca e cazul
				propValue.erase(std::remove(propValue.begin(), propValue.end(), '\n'), propValue.end()); // scoate enter final din string

				SimpleObject obiect;
				obiect.propertyName=propName;
				obiect.propertyValue=propValue;
				objects.push_back(obiect);
				//cout << propName << " ... " << propValue << endl;
			}
	}

	return objects;
}



FileResult stn_readFile(char *path){
	FileResult composedData;
	ifstream fin;                          // Declaring an input stream object
	string outPut;
	string result="";
	fin.open(path, ios::in);
	if(fin.is_open())                      // If it opened successfully
		{

			while (getline(fin, outPut)) {
				composedData.addLine(outPut);
			}
			fin.close();
			return composedData;
		}
	else{
		printf("FAILED TO LOAD FILE %s", path);
	}
	return composedData;
}


//void stn_openFile(char *path){
//	cout << "|||||||||||| READ FILE " << path << endl;
//	FILE *f=fopen(path, "r");
//	char ch;
//
//	if (f){
//	  printf("fopen success\n");
//	  while( ( ch = fgetc(f) ) != EOF ){
//	        printf("%c",ch);
//	  }
//
//	}else{
//		printf("FAILED TO OPEN FILE \n");
//	}
//
//	fclose(f);
//}

//STRING UTILS:
char *stn_getCurrentFolder(){
	char cCurrentPath[FILENAME_MAX];
	return GetCurrentDir(cCurrentPath, sizeof(cCurrentPath));
}



vector<string> splitChar(char p_str[], char delimiter[]){


	vector<string> items;
	//duplicate the origibnal input:
	int ngt=strlen(p_str);
	cout << ngt << "items" << endl;
	char str[ngt];
	strcpy(str, p_str);
	cout << "split duplicate" << str << endl;
	  char * pch;
	  //printf ("Splitting string \"%s\" into tokens:\n",str);
	  pch = strtok (str,delimiter);
	  while (pch != NULL)
	  {
	    //printf ("%s\n",pch);
		string strng = pch;
	    items.push_back(strng);
	    pch = strtok (NULL, delimiter);
	  }

//	  for(int i=0; i<(int)items.size(); i++){
//	  			cout << "returned: " << items.at(i)<< endl;
//	  		}

	return items;
}

//convert an absolute path to a relativeToApplication path
string stn_absoluteToRelative(char absolutePath[], char delimiter[]){

	char cCurrentPath[FILENAME_MAX];
	char *appFolder=GetCurrentDir(cCurrentPath, sizeof(cCurrentPath));

	vector<string> appFolders=splitChar(appFolder, delimiter);
	vector<string> fileFolders=splitChar(absolutePath, delimiter);
	string prefix="";
	string suffix="";


	int num=0;
	while(appFolders.at(num)==fileFolders.at(num)){
		cout << appFolders.at(num) << " same with " << fileFolders.at(num) << endl;
		num++;
	}


	cout << "first" << num << "folders are the same" << endl;


	//inlocuim
	for(int i=num; i<(int)appFolders.size(); i++){
					prefix.append("../");
					cout << "backward from " << appFolders.at(i) << " ../ step " << i-num << endl;
				}

	//toate fisierele mai putin utimul
	for(int i=num; i<(int)fileFolders.size()-1; i++){ //-1 pentryu exceptie la fisier
						//strcat(prefix, "/..");
						suffix.append(fileFolders.at(i));
						suffix.append("/");
						cout << "toward to " << fileFolders.at(i) << " --> step " << i-num << endl;
					}
	//adaugam ultimul fisier
	suffix.append(fileFolders.at(fileFolders.size()-1));


	cout << prefix << suffix << endl;

	return prefix.append(suffix);
	//
//	cout << absolutePath << endl;

	//printf("given absote %s", absolutePath.c_str());

}







#endif /* FILEUTILS_H_ */
